package views;

import views.panels.PanelGeneral;
import logicBusiness.AdministradorBL;
import java.awt.BorderLayout;
import javax.swing.ImageIcon;
import logicBusiness.EstudianteBL;
import logicBusiness.ProfesorBL;
import logicBusiness.UsuarioBL;
import models.Estudiante;
import models.Profesor;
import models.Usuario;
import java.util.Collection;
import java.util.Iterator;
import javax.swing.JOptionPane;

/**
 *
 * @author eagle
 */
public class InterfazCrearUSuario extends javax.swing.JFrame {

    private ImageIcon icono;
    private Long indiceDocEst[];

    /** Creates new form InterfazCrearUSuario */
    public InterfazCrearUSuario() {
        initComponents();
        PanelGeneral panel = new PanelGeneral();
        this.add(panel, BorderLayout.EAST);
        icono = new ImageIcon(getClass().getResource("/Imagenes/icon.gif"));
        this.setIconImage(icono.getImage());
        jLabel6.setVisible(false);
        jLabel7.setVisible(false);
        CTNombre.setVisible(false);
        CTApellido.setVisible(false);

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        CTNick = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        CPContraseña = new javax.swing.JPasswordField();
        jLabel5 = new javax.swing.JLabel();
        CPConfirmarContra = new javax.swing.JPasswordField();
        jLabel1 = new javax.swing.JLabel();
        CBTipoUsuario = new javax.swing.JComboBox();
        jButton1 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        CBAsignar = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        CTNombre = new javax.swing.JTextField();
        CTApellido = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Crear Usuario");
        setName("Crear Usuario"); // NOI18N

        jLabel3.setText("Nick:");

        jLabel4.setText("Contraseña:");

        jLabel5.setText("Confirmar Contraseña:");

        jLabel1.setText("Tipo de usuario:");

        CBTipoUsuario.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Escoja:", "Estudiante", "Profesor", "Administrador" }));
        CBTipoUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CBTipoUsuarioActionPerformed(evt);
            }
        });

        jButton1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jButton1.setText("Crear");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel2.setText("Asignar a:");

        CBAsignar.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Seleccione" }));

        jLabel6.setText("Nombre");

        jLabel7.setText("Apellido");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(124, 124, 124)
                        .addComponent(CBTipoUsuario, 0, 368, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4)
                            .addComponent(jLabel5)
                            .addComponent(jLabel2)
                            .addComponent(jLabel6)
                            .addComponent(jLabel7))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(CPContraseña, javax.swing.GroupLayout.DEFAULT_SIZE, 368, Short.MAX_VALUE)
                            .addComponent(CTNick, javax.swing.GroupLayout.DEFAULT_SIZE, 368, Short.MAX_VALUE)
                            .addComponent(CPConfirmarContra, javax.swing.GroupLayout.DEFAULT_SIZE, 368, Short.MAX_VALUE)
                            .addComponent(CBAsignar, 0, 368, Short.MAX_VALUE)
                            .addComponent(CTNombre, javax.swing.GroupLayout.DEFAULT_SIZE, 368, Short.MAX_VALUE)
                            .addComponent(CTApellido, javax.swing.GroupLayout.DEFAULT_SIZE, 368, Short.MAX_VALUE))))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(196, Short.MAX_VALUE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(179, 179, 179))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(CBTipoUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(CTNick, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(CPContraseña, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(CPConfirmarContra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(CBAsignar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(CTNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(CTApellido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addGap(32, 32, 32)
                .addComponent(jButton1)
                .addContainerGap(23, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if (String.valueOf(CPContraseña.getPassword()).equals(String.valueOf(CPConfirmarContra.getPassword()))) {
            if (CBTipoUsuario.getSelectedIndex() == 1) {//crear usuario a estudiante
                if (CBAsignar.getItemCount() == 1) {
                    JOptionPane.showMessageDialog(this, "Seleccione un estudiante", "", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    asignarUsuarioAEstudiante();
                }
            }
            if (CBTipoUsuario.getSelectedIndex() == 2) {//crear usuario a prf
                if (CBAsignar.getItemCount() == 1) {
                    JOptionPane.showMessageDialog(this, "Seleccione un profesor", "Profesores sin usuario: 0", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    asignarUsuarioAProfesor();
                }
            }
            if (CBTipoUsuario.getSelectedIndex() == 3) {//crear usuario a ad
                asignarUsuarioAAdministrador();
            }
        } else {
            JOptionPane.showMessageDialog(this, "Claves no concordantes");
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void CBTipoUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CBTipoUsuarioActionPerformed

        if (CBTipoUsuario.getSelectedIndex() == 1) {
            jLabel6.setVisible(false);
            jLabel7.setVisible(false);
            CTNombre.setVisible(false);
            CTApellido.setVisible(false);
            poblarComboEstudiantes();
            if (CBAsignar.getItemCount() == 1) {
                JOptionPane.showMessageDialog(this, "Estudiantes sin usuario: 0", "No hay estudiantes sin usuario", JOptionPane.INFORMATION_MESSAGE);
            }
        }
        if (CBTipoUsuario.getSelectedIndex() == 2) {
            jLabel6.setVisible(false);
            jLabel7.setVisible(false);
            CTNombre.setVisible(false);
            CTApellido.setVisible(false);
            poblarComboProfesores();
            if (CBAsignar.getItemCount() == 1) {
                JOptionPane.showMessageDialog(this, "Profesores sin usuario: 0", "No hay Profesores sin usuario", JOptionPane.INFORMATION_MESSAGE);
            }
        }
        if (CBTipoUsuario.getSelectedIndex() == 3) {
            poblarComboAdministradores();
        }
    }//GEN-LAST:event_CBTipoUsuarioActionPerformed
    private void poblarComboEstudiantes() {
        EstudianteBL ebo = new EstudianteBL();
//        Collection<Estudiante> e = ebo.encontrarEstudiantesSinUsuario();
        CBAsignar.setModel(new javax.swing.DefaultComboBoxModel(new String[]{"Seleccione"}));
//        Iterator<Estudiante> itp = e.iterator();
//        if (e.size() > 0) {
//            indiceDocEst = new Long[e.size()];
//        }
        int i = 0;
//        while (itp.hasNext()) {
//            Estudiante p = itp.next();
////            indiceDocEst[i] = p.getDocEstudiante();
////            CBAsignar.addItem(p.getApellidoEst() + " " + p.getNombreEst() + " [Doc: " + p.getDocEstudiante() + "]");
//            i++;
//        }
    }

    private void asignarUsuarioAEstudiante() {
        UsuarioBL ubo = new UsuarioBL();
//        Usuario u = ubo.crearUsuario(CTNick.getText(), String.valueOf(CPContraseña.getPassword()), "Estudiante");
        EstudianteBL ebo = new EstudianteBL();
//        ebo.asignarUsuarioAEstudiante(indiceDocEst[CBAsignar.getSelectedIndex() - 1], CTNick.getText());
        poblarComboEstudiantes();
        operacionFinal();
    }

    private void poblarComboAdministradores() {
        CBAsignar.setModel(new javax.swing.DefaultComboBoxModel(new String[]{"No Aplica"}));
        CBAsignar.setEnabled(false);
        jLabel6.setVisible(true);
        jLabel7.setVisible(true);
        CTNombre.setVisible(true);
        CTApellido.setVisible(true);
    }

    private void asignarUsuarioAProfesor() {
        UsuarioBL ubo = new UsuarioBL();
//        Usuario u = ubo.crearUsuario(CTNick.getText(), String.valueOf(CPContraseña.getPassword()), "Profesor");
        ProfesorBL ebo = new ProfesorBL();
//        ebo.asignarUsuarioAProfesor(indiceDocEst[CBAsignar.getSelectedIndex() - 1], CTNick.getText());
        poblarComboProfesores();
        operacionFinal();
    }

    private void poblarComboProfesores() {
        ProfesorBL pbo = new ProfesorBL();
//        Collection<Profesor> p = pbo.encontrarProfesoresSinUsuario();
        CBAsignar.setModel(new javax.swing.DefaultComboBoxModel(new String[]{"Seleccione"}));
//        Iterator<Profesor> itp = p.iterator();
//        if (p.size() > 0) {
//            indiceDocEst = new Long[p.size()];
//        }
        int i = 0;
//        while (itp.hasNext()) {
//            Profesor profeActual = itp.next();
////            indiceDocEst[i] = profeActual.getDocProfesor();
////            CBAsignar.addItem(profeActual.getApellidoProfesor() + " " + profeActual.getNombreProfesor() + " [Doc: " + profeActual.getDocProfesor() + "]");
//            i++;
//        }
    }

    private void asignarUsuarioAAdministrador() {
        UsuarioBL ubo = new UsuarioBL();
//            Usuario u = ubo.crearUsuario(CTNick.getText(), String.valueOf(CPContraseña.getPassword()), "Admin");
        AdministradorBL ebo = new AdministradorBL();
//        ebo.crearAdministrador(CTNombre.getText(), CTApellido.getText(), CTNick.getText());
        operacionFinal();
    }

    public void operacionFinal() {
        JOptionPane.showMessageDialog(this, "El usuario se asignado satisfactoriamente", "Operacion Existosa", JOptionPane.INFORMATION_MESSAGE);
        CTNick.setText("");
        CPContraseña.setText("");
        CPConfirmarContra.setText("");
        CTNombre.setText("");
        CTApellido.setText("");

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new InterfazCrearUSuario().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox CBAsignar;
    private javax.swing.JComboBox CBTipoUsuario;
    private javax.swing.JPasswordField CPConfirmarContra;
    private javax.swing.JPasswordField CPContraseña;
    private javax.swing.JTextField CTApellido;
    private javax.swing.JTextField CTNick;
    private javax.swing.JTextField CTNombre;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    // End of variables declaration//GEN-END:variables
}
